<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="queryDep">
        <el-form-item>
          <el-input v-model="queryDep.name" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="selectDep">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addDep">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="intro" label="部门介绍" width="120" sortable>
      </el-table-column>
      <el-table-column prop="createTime" label="部门创建时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="updateTime" label="部门更新时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" sortable>
      </el-table-column>
      <el-table-column prop="path" label="上级路径" sortable>
      </el-table-column>
      <el-table-column prop="state" label="部门状态" :formatter="formatState" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="editDep(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="delDep(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        :total="total"
        style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑或修改界面-->
    <el-dialog :title="title" :visible.sync="depFormVisible" :close-on-click-modal="false">
      <el-form :model="depForm" label-width="80px" :rules="depFormRules" ref="depForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="depForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门介绍">
          <el-input v-model="depForm.intro"></el-input>
        </el-form-item>
        <el-form-item label="部门经理">
        <!--<el-input v-model="depForm.managerId"></el-input>-->
          <el-select v-model="depForm.manager" value-key="id" clearable filterable placeholder="请选择">
            <el-option
                v-for="item in emps"
                :key="item.id"
                :label="item.username"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
        <!--<el-input v-model="depForm.parentId"></el-input>-->
        <!--props中label用来定义选项字段是什么，value用来定义值是什么-->
          <el-cascader
              v-model="depForm.parent"
              :options="depTree"
              :props="{
                checkStrictly: true,
                label: 'name',
                value: 'id'
              }"
              @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="depForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="depFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="depFormSubmit" :loading="depFormLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from "../../common/js/util";
import {batchRemoveUser, editUser} from "../../api/api";

export default {
  name: "Department",

  data(){
    return{
      queryDep:{
        name: '',
      },
      departments: [], //部门
      listLoading: false, //加载
      sels: [], //选择多项
      total: 0, //Department数据总数
      currentPage: 1, //当前默认页面
      pageSize: 10, //默认页面条数
      title: "新增", //表单名
      depFormVisible: false, //默认关闭弹出框
      //编辑或修改界面数据
      depForm: {
        id: null,
        name: null,
        intro: null,
        managerId: null,
        parentId: null,
        path: null,
        state: null,
        manager: null,
        parent: null,
      },
      //表单验证
      depFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ]
      },
      depFormLoading: false, //不显示加载
      emps: [], //部门经理
      depTree: [], //级联选择
    }
  },

  methods: {
    //查询Department
    selectDep(){
      this.currentPage = 1
      this.listLoadingDep()
    },
    //增加Department
    addDep(){
      this.loadDepTree()
      //更改表单名
      this.title = "新增"
      //1.清空表单数据
      this.depForm = {
        id: null,
        name: null,
        intro: null,
        managerId: null,
        parentId: null,
        path: null,
        state: null
      }
      //2.打开弹出框
      this.depFormVisible = true
    },

    //选择项发生改变时触发
    selsChange(val){
      this.sels = val
    },

    //状态显示转换
    formatState: function (row, column) {
      return row.state == 1 ? '启用' : row.state == 0 ? '禁用' : '未知';
    },

    //编辑Department数据
    editDep(index,row){
      this.loadDepTree()
      //更改表单名
      this.title = "编辑"
      //1.数据回显
      Object.assign(this.depForm,row)
      //2.打开弹出框
      this.depFormVisible = true
      //3.对上级部门做数据回显
      this.depForm.parent = row.parentId
    },

    //删除Department数据
    delDep(index,row){
      //通过表单验证
      this.$confirm('确认删除数据吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.delete("/dep/" + row.id).then((res) => {
          this.depFormLoading = false;
          if (res.data.success){
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }
          else {
            this.$message.error(res.data.message)
          }
          this.listLoadingDep()
        });
      });
    },

    //加载Department列表数据
    listLoadingDep(){
      //加载列表
      this.listLoading = true;
      //封装数据
      let query = {
        currentPage: this.currentPage, //当前页面
        pageSize: this.pageSize, //页面条数
        name: this.queryDep.name, //关键字查询
      }
      //发送请求获取Department列表数据
      this.$http.post('/dep',query).then(res=>{
        //数据总条数
        this.total = res.data.count
        //Department列表数据
        this.departments = res.data.data
        //关闭加载列表
        this.listLoading = false;
      })
    },

    //批量删除
    batchRemove(){
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        // let para = { ids: ids };
        this.$http.patch("/dep",ids).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.listLoadingDep();
        });
      }).catch(() => {

      });
    },

    //当前页条数
    handleSizeChange(val){
      this.pageSize = val
      this.listLoadingDep()
    },

    //指向当前页
    handleCurrentChange(val){
      this.currentPage = val
      this.listLoadingDep()
    },

    //提交弹出框
    depFormSubmit(){
      this.$refs.depForm.validate((valid) => {
        if (valid) {
          //通过表单验证
          this.$confirm('确认提交数据吗？', '提示', {}).then(() => {
            //用户点击了确认
            this.depFormLoading = true;
            //对parent做特殊处理
            //选择级联后的情况 1.null 2.[1]或[1,2]
            //加if判断条件，屏蔽null
            if (this.depForm.parent){
              //取出数组中的最后一个值
              let index = this.depForm.parent.length
              //改变parent的数据结构
              this.depForm.parent = {
                id: this.depForm.parent[index-1]
              }
            }

            this.$http.put("/dep",this.depForm).then((res) => {
              this.depFormLoading = false;
              if (res.data.success){
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
              }
              else {
                this.$message.error(res.data.message)
              }
              this.depFormVisible = false
              this.depFormLoading = false
              this.listLoadingDep()
            });
          });
        }
      });
    },
    //获取所有员工
    loadEmployees(){
    //发送请求，获取所有员工
      this.$http.get("/emp").then(res => {
        this.emps = res.data
      })
    },

    //加载部门树，级联选择，父亲查儿子
    loadDepTree(){
      this.$http.get("/dep/tree").then(res => {
        this.depTree = res.data
      })
    },
    handleChange(){

    }

  },

  mounted() {
    this.listLoadingDep();
    this.loadEmployees();
  }
}
</script>

<style scoped></style>